package com.yykj.hospital.server.service.qrcode.impl;

import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.yykj.common.constant.RedisConstant;
import com.yykj.common.enums.ResultEnums;
import com.yykj.common.exception.NormalException;
import com.yykj.common.service.RedisService;
import com.yykj.common.util.GsonUtil;
import com.yykj.common.util.HttpUtil;
import com.yykj.common.util.LocalUploadFile;
import com.yykj.hospital.server.dto.wx.WxAccessTokenResult;
import com.yykj.hospital.server.model.entity.qrcode.DoctorQrcode;
import com.yykj.hospital.server.model.repository.qrcode.DoctorQrcodeRepository;
import com.yykj.hospital.server.service.qrcode.QrcodeService;
import com.yykj.pay.center.client.dto.ClientPayConfigDTO;
import com.yykj.pay.center.client.feign.PayFeignClient;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

@Service
public class QrcodeServiceImpl implements QrcodeService {

    @Value("${wx.envVersion}")
    private String wxEnv;

    @Override
    public String getDoctorWxQrcode(DoctorQrcode doctorQrcode) {
        try {
            String accessToken = getAccessToken(doctorQrcode.getHospitalId());
            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("scene", "qrId=" + doctorQrcode.getQrId());
            jsonObject.put("page", "subpkg/index/doctor_info");
            jsonObject.put("env_version", wxEnv);
            InputStream inputStream = Unirest.post(url)
                    .header("accept", "application/json")
                    .header("content-type", "application/json")
                    .body(jsonObject).asBinary().getBody();
            String fileName =  doctorQrcode.getQrId() + ".jpg";
            String filePath = "./qrcode/";
            File pathFile = new File(filePath);
            if(!pathFile.exists()){
                pathFile.mkdirs();
            }
            String fullName = filePath + fileName;
            FileOutputStream fileOutputStream = new FileOutputStream(filePath + fileName);
            byte[] b = new byte[1024];
            int i = 0;
            while ((i = inputStream.read(b)) != -1) {
                fileOutputStream.write(b);
            }
            fileOutputStream.flush();
            inputStream.close();
            fileOutputStream.close();
            return fullName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String generateDoctorQrcode(Integer hospitalId,String doctorId,String jsonExt) {
        DoctorQrcode doctorQrcode = qrcodeRepository.findByDoctorId(doctorId);
        if(doctorQrcode == null){
            doctorQrcode = new DoctorQrcode();
        }
        doctorQrcode.setHospitalId(hospitalId);
        doctorQrcode.setDoctorId(doctorId);
        doctorQrcode.setExt(jsonExt);
        doctorQrcode = qrcodeRepository.save(doctorQrcode);
        String filename =  getDoctorWxQrcode(doctorQrcode);
        if(filename!=null){
           return  LocalUploadFile.uploadFile(new File(filename));
        }else{
            throw new NormalException(ResultEnums.DOCTOR_QR_CODE_ERROR);
        }
    }

    @Override
    public DoctorQrcode getDoctorQrcodeParam(Integer id) {
        return qrcodeRepository.findById(id).orElseThrow(() -> new NormalException(ResultEnums.NOT_EXIST));
    }

    private String getAccessToken(Integer hospitalId) throws UnirestException {
        String key = "wx_access_token";
        String result = redisService.get(key);
        if (!StringUtils.isEmpty(result)) {
            return result;
        } else {
            ClientPayConfigDTO clientPayConfigDTO = payFeignClient.get(String.valueOf(hospitalId));
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+clientPayConfigDTO.getClientAppId()+"&secret="+clientPayConfigDTO.getClientSecret();
            String s = HttpUtil.get(url);
            WxAccessTokenResult wxAccessTokenResult = GsonUtil.fromJson(s, WxAccessTokenResult.class);
            result = wxAccessTokenResult.getAccess_token();
            redisService.set(key, result, RedisConstant.EXPIRE_HOUR);
        }
        return result;
    }

    private RedisService redisService;

    private DoctorQrcodeRepository qrcodeRepository;

    private PayFeignClient payFeignClient;

    @Autowired
    public void setRedisService(RedisService redisService) {
        this.redisService = redisService;
    }

    @Autowired
    public void setQrcodeRepository(DoctorQrcodeRepository qrcodeRepository) {
        this.qrcodeRepository = qrcodeRepository;
    }

    @Autowired
    public void setPayFeignClient(PayFeignClient payFeignClient) {
        this.payFeignClient = payFeignClient;
    }
}
